package com.summer.framework.core.factory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Description: bean工厂类
 * @auther Ice Yang
 * Date 2025/7/2 13:31
 */
@Component
public class SummerBeanFactory implements ApplicationContextAware {

    private final static Logger LOGGER = LoggerFactory.getLogger(SummerBeanFactory.class);

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SummerBeanFactory.applicationContext = applicationContext;
    }

    /**
     * 根绝类注入名称获得对象
     * @param name
     * @return
     */
    public static Object getBeanByName(String name){
        if(name == null || name.isEmpty()){
            LOGGER.error("object name is empty");
            return null;
        }
        return applicationContext.getBean(name);
    }

    /**
     * 根绝类注入名称获得对象
     * @param name
     * @return
     */
    public static <T> T getBeanByName(String name,Class<T> clazz){
        if(name == null || name.isEmpty()){
            LOGGER.error("object name is empty");
            return null;
        }
        Object obj = applicationContext.getBean(name);
        // 转为对应的对象
        if(clazz.isInstance(obj)){
            return clazz.cast(obj);
        }
        return null;
    }

    /**
     * 根据Class获得对象
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBeanByClass(Class<T> clazz){
        if(clazz == null){
            LOGGER.error("class is not empty");
            return null;
        }
        return applicationContext.getBean(clazz);
    }
}
